import LivePlayer from '@/components/LivePlayer';
import { uploadFormData } from '@/services/FileService';
import { getSelfGrowthId } from '@/services/MeetingService';
import { getM7sConfig } from '@/services/ObsService';
import {
  appPreview,
  getAppOutPut,
  getOutputList,
  reconnectOutPut,
  updateAppOutPut,
} from '@/services/OutputSourceSerivce';
import { addVideo, scanSegmentRecord } from '@/services/RecordService';
import { mixConfig, mixOutputSource, mixType, responseType } from '@/types';
import { useModel } from '@@/exports';
import {
  CloseSquareOutlined,
  NotificationOutlined,
  RedoOutlined,
  ScissorOutlined,
  SettingOutlined,
  SoundOutlined,
  SyncOutlined,
  VideoCameraFilled,
} from '@ant-design/icons';
import { useDrag, useDrop } from 'ahooks';
import { Collapse, CollapseProps, message, Slider, Tag } from 'antd';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';
import SVG from 'react-inlinesvg';
import styles from './style.less';
import './styles.less';

export interface clientLiveType {
  organizationName: string;
  id: number;
  equipmentName: string;
  brand: string;
  ip: string;
  port: number;
  organizationId: number;
  userName: string;
  password: string;
  vag: null | string;
  version: null;
  autoRec: null;
  streamUrl: null;
  outType: number;
  state: number;
  createUser: number;
  createTime: Date;
  updateUser: number;
  updateTime: Date;
  deleteTime: null;
  isDeleted: number;
  status: number;
}

function computerHeight(width: number): string {
  return ((width / 1920) * 1080).toFixed(1);
}

const converMixType = (mixType: number): number => {
  if (mixType < 5) return mixType;
  if (mixType === 13) return 4;
  if (mixType > 900) return 2;
  return 1;
};
type liveFixType = {
  config?: clientLiveType;
  preview: { x: number; y: number };
  isHover: boolean;
  startDrag: boolean;
};

type organizationType = {
  organizationId: number;
  organizationName: string;
  item: clientLiveType[];
};
const convertDevice = (
  list: clientLiveType[],
  findFuc: (item: clientLiveType, after: clientLiveType) => boolean,
  pushFuc: (after: clientLiveType) => organizationType,
): organizationType[] => {
  return list.reduce((pre, after) => {
    const index = pre.findIndex((item) => findFuc(item, after));
    if (index === -1) {
      pre.push(pushFuc(after));
    } else {
      pre[index].item.push(after);
    }
    return pre;
  }, []);
};

const rateItem = [
  {
    label: '主码',
    value: 5000,
  },
  {
    label: '子码',
    value: 5001,
  },
];

const LiveFix = ({
  config,
  preview,
  isHover,
  startDrag,
}: {
  config: clientLiveType;
  preview: { x: number; y: number };
  isHover: boolean;
  startDrag: boolean;
}) => {
  return (
    <>
      {config && config.state === 0 && isHover && !startDrag && (
        <div
          style={{
            position: 'fixed',
            width: '500px',
            backgroundColor: '#fff',
            height: computerHeight(500) + 'px',
            left: isHover ? `${preview.x}px` : 0,
            top: isHover ? `${preview.y}px` : 0,
            zIndex: 1000,
            display: 'flex',
          }}
        >
          {config.ip && (
            <LivePlayer
              server={config.ip}
              streamKey={'sub'}
              type="Encoder_WebRTC"
              visible={true}
              controls={false}
              muted={true}
            />
          )}
        </div>
      )}
    </>
  );
};

const DragItem = ({
  config,
  active,
  setInputDrag,
  setLiveFixData,
  liveFixData,
}: {
  config: clientLiveType;
  active: (client: clientLiveType) => void;
  setInputDrag: (isDrag: boolean) => void;
  setLiveFixData: (live: liveFixType) => void;
  liveFixData: liveFixType;
}) => {
  const [isHover, setHover] = useState(false);
  const [preview, setPreview] = useState<{ x: number; y: number }>({});
  const [startDrag, setStartDrag] = useState(false);
  const [isPlay, setIsPlay] = useState(false);
  const [isDragging, setIsDragging] = useState(false);
  const drag = useRef(null);
  let propsDrag = {};
  useDrag(config, drag, {
    onDragStart: () => {
      if (config.state === 0) setIsDragging(true);
    },
    onDragEnd: () => {
      if (config.state === 0) setIsDragging(false);
    },
  });
  if (config.state === 0) {
    propsDrag = {
      draggable: true,
      onClick: () => {
        if (config.state !== 0) return;
        active(config);
      },
      onDragStart: () => {
        setStartDrag(true);
        setInputDrag(true);
        liveFixData.startDrag = true;
        setLiveFixData({ ...liveFixData });
      },
      onDragEnd: () => {
        setStartDrag(false);
        setInputDrag(false);
        setHover(false);

        liveFixData.startDrag = false;
        liveFixData.isHover = false;
        setLiveFixData({ ...liveFixData });
      },

      onMouseOver: (e) => {
        if (!isHover) {
          const { x, y, width } = e.currentTarget.getBoundingClientRect();
          setIsPlay(true);
          setHover(true);
          liveFixData.preview = { x: x + width + 16, y };
          liveFixData.config = config;
          liveFixData.isHover = true;
          setLiveFixData({ ...liveFixData });
        }
        e.preventDefault();
      },
      onMouseOut: (e) => {
        setHover(false);
        setIsPlay(false);

        liveFixData.isHover = false;
        setLiveFixData({ ...liveFixData });
      },
    };
  }
  const opacity = isDragging ? 0.4 : 1;

  return (
    <div
      ref={drag}
      {...propsDrag}
      style={{
        width: '100%',
        height: '100%',
        position: 'relative',
        padding: '10px',
        marginBottom: '10px',
        background: config.state === 0 ? '#429eff' : '#7d8999',
        zIndex: 100000,
        borderRadius: '5px',
        cursor: isHover ? 'move' : 'unset',
        opacity,
      }}
    >
      {config.equipmentName}
    </div>
  );
};

const DropContainer = ({
  mix,
  index,
  inputDrag,
  onDrop,
  mixType,
}: {
  mix: mixType;
  index: number;
  inputDrag: boolean;
  onDrop: (config: mixType) => Promise<void>;
  mixType: number;
}) => {
  const dropRef = useRef(null);
  const [isActive, setIsActive] = useState<boolean>(false);
  const [showTools, setShowTools] = useState<boolean>(false);

  const mainPort = mixType === 1 || (mixType > 900 && index === 0);
  useDrop(dropRef, {
    onDom: async (data: clientLiveType, e) => {
      console.log('content', data);
      setIsActive(false);
      let mixData: mixType = {
        address: data.ip,
        volume: 0,
        port: mainPort ? 5000 : 5001,
      };
      await onDrop(mixData);
    },
    onDragEnter: () => setIsActive(true),
    onDragLeave: () => setIsActive(false),
  });
  let color = 'darkgreen';
  if (isActive) {
    color = 'darkgreen';
  } else {
    color = 'red';
  }
  return (
    <div
      key={index}
      className={styles.dropContain}
      onMouseOver={() => setShowTools(true)}
      onMouseOut={() => setShowTools(false)}
    >
      <div
        className={styles.dragWrap}
        ref={dropRef}
        style={{
          width: '100%',
          height: '100%',
          backgroundColor: '#c2c2c260',
          border: '1px solid #000',
          position: 'absolute',
          zIndex: 100,
          display: inputDrag ? 'flex' : 'none',
          color,
        }}
      >
        <span style={{ margin: 'auto' }}>
          {isActive ? '松开放入' : '拖拽到此处放入'}
        </span>
      </div>
      <div
        style={{
          position: 'absolute',
          width: '100%',
          top: 0,
          left: 0,
          backgroundColor: '#3d3d3d',
          flexWrap: 'nowrap',
          overflowX: 'hidden',
          zIndex: 10,
          display: showTools && !inputDrag && mix.address ? 'flex' : 'none',
        }}
      >
        <Tag
          color="blue"
          style={{
            height: '25px',
            margin: 'auto 10px',
          }}
        >
          {mix.address && mix.port === 5000 ? '主码' : '子码'}
        </Tag>
        {mix.volume === 0 ? <NotificationOutlined /> : <SoundOutlined />}
        <Slider
          style={{ flex: '0 1 100px', marginLeft: '10px' }}
          max={100}
          min={0}
          step={1}
          onChange={async (e) => {
            mix.volume = e;
            await onDrop({ ...mix });
          }}
          value={mix.volume}
        />

        <div style={{ flex: '1', textAlign: 'right' }}>
          <CloseSquareOutlined
            style={{ fontSize: '30px' }}
            onClick={async () => {
              mix.volume = 0;
              mix.address = '';
              mix.port = mainPort ? 5000 : 5001;
              await onDrop({ ...mix });
            }}
          />
        </div>
      </div>
      <div
        style={{
          width: '100%',
          height: '100%',
          position: 'absolute',
          zIndex: 5,
        }}
      >
        {mix.address && (
          <LivePlayer
            server={mix.address}
            streamKey={mix.port === 5000 ? 'main' : 'sub'}
            type="Encoder_WebRTC"
            visible={true}
            controls={false}
            muted={mix.volume === 0}
          />
        )}
      </div>
    </div>
  );
};

const LeftInput = ({
  liveClients,
  active,
  setInputDrag,
  reloadInList,
  setLiveFixData,
  liveFixData,
}: {
  liveClients: organizationType[];
  active: (clientLive: clientLiveType) => void;
  setInputDrag: (isDrag: boolean) => void;
  reloadInList: () => void;
  setLiveFixData: (livefix: liveFixType) => void;
  liveFixData: liveFixType;
}) => {
  const items: CollapseProps['items'] = liveClients.map((client) => {
    return {
      key: client.organizationId,
      label: (
        <>
          <SettingOutlined style={{ marginRight: '10px' }} />
          {client.organizationName}
        </>
      ),
      children: client.item.map((clientItem) => {
        return (
          <DragItem
            key={clientItem.id}
            config={clientItem}
            setInputDrag={setInputDrag}
            setLiveFixData={setLiveFixData}
            liveFixData={liveFixData}
            active={active}
          />
        );
      }),
      style: {
        backgroundColor: '#429eff',
      },
    };
  });

  return (
    <div className={styles.leftInput}>
      <div
        style={{
          width: '100%',
          height: '50px',
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
        }}
      >
        <div style={{ width: '90%', paddingLeft: '10px' }}>资源输入</div>
        <div style={{ paddingRight: '10px' }}>
          <SyncOutlined onClick={() => reloadInList()} />
        </div>
      </div>
      <div>
        <Collapse
          className={styles.collapseCus}
          style={{ height: '100%' }}
          defaultActiveKey={'1'}
          accordion={true}
          expandIconPosition={'end'}
          items={items}
        />
      </div>
    </div>
  );
};

const RightInput = ({
  liveClients,
  active,
  setOutputConfig,
  reloadOutList,
}: {
  liveClients: organizationType[];
  active: (clientLive: clientLiveType) => void;
  setOutputConfig: (outConfig: mixOutputSource) => void;
  reloadOutList: () => void;
}) => {
  const activeOutput = async (client: clientLiveType) => {
    const result: responseType<mixOutputSource> = await getAppOutPut(client.ip);
    console.log(result, 'result');
    if (result.success) {
      active(client);
      // const mixType = converMixType(result.data.outputSource[0].mixType)
      const length = result.data.outputSource[0].mixConfig.length;
      if (length < 4) {
        result.data.outputSource[0].mixConfig.push(
          ...Array(4 - length).fill({
            volume: 0,
            address: '',
          }),
        );
      }
      // if (length < 0) {
      //     result.data.outputSource[0].mixConfig.splice(mixType)
      // }
      setOutputConfig(result.data);
    } else {
      message.error('获取设备信息失败');
      return;
    }
  };

  const items: CollapseProps['items'] = liveClients.map((client) => {
    return {
      key: client.organizationId,
      label: (
        <div style={{ width: '100%', height: '100%' }}>
          <SettingOutlined style={{ marginRight: '10px' }} />
          {client.organizationName}
        </div>
      ),
      children: client.item.map((clientItem) => {
        return (
          <div
            key={clientItem.id}
            onClick={async () => {
              if (clientItem.status !== 0) return;
              await activeOutput(clientItem);
            }}
            style={{
              width: '100%',
              height: '100%',
              position: 'relative',
              padding: '10px',
              marginBottom: '10px',
              background: clientItem.status === 0 ? '#429eff' : '#7d8999',
              borderRadius: '5px',
            }}
          >
            {clientItem.equipmentName}
          </div>
        );
      }),
      style: {
        backgroundColor: '#429eff',
      },
    };
  });
  return (
    <div className={styles.leftInput}>
      <div className={styles.topSearch}>
        <div className={styles.label}>资源输出</div>
        <div className={styles.refresh}>
          <SyncOutlined onClick={() => reloadOutList()} />
        </div>
      </div>
      <div>
        <Collapse
          className={styles.collapseCus}
          style={{ height: '100%' }}
          defaultActiveKey={'1'}
          accordion={true}
          expandIconPosition={'end'}
          items={items}
        />
      </div>
    </div>
  );
};

const RectBox = ({
  mixType,
  changeRect,
}: {
  mixType: number; //选中
  changeRect: (rect: number) => void;
}) => {
  const [rectFixBox, setRectFixBox] = useState<boolean>(false);
  const minList = [1, 2, 4, 13];
  const maxList = [921, 922, 923, 924];
  return (
    <>
      {minList.map((item) => {
        return (
          <div
            key={item}
            className={styles.rectBox}
            onClick={() => changeRect(item)}
          >
            <div
              className={`${styles.rectangle} ${styles[`rect${item}`]} ${
                mixType === item ? styles.active : ''
              }`}
            />
          </div>
        );
      })}
      <div className={styles.rectBox}>
        <div
          className={`${styles.rectangle} ${
            styles[`${mixType > 900 ? 'rect' + mixType : 'rect921'}`]
          } ${mixType > 900 ? styles.active : ''}  ${styles.rectSelect}`}
          style={{ position: 'relative' }}
          onMouseOver={() => setRectFixBox(true)}
          onMouseOut={() => setRectFixBox(false)}
        >
          {rectFixBox && (
            <div className={styles.rectFixBox}>
              {maxList.map((item) => {
                return (
                  <div
                    key={item}
                    className={styles.rectBox}
                    onClick={() => changeRect(item)}
                  >
                    <div
                      className={`${styles.rectangle} ${
                        styles[`rect${item}`]
                      } ${mixType === item ? styles.active : ''}`}
                    />
                  </div>
                );
              })}
            </div>
          )}
        </div>
      </div>
    </>
  );
};

const CenterVideo = ({
  config,
  inputDrag,
  isPlay,
  outputConfig,
  setOutputConfig,
}: {
  config?: clientLiveType;
  inputDrag: boolean;
  isPlay: boolean;
  outputConfig: mixOutputSource;
  setOutputConfig: (output: mixOutputSource) => void;
}) => {
  const videoRef = useRef(null);
  const [visible, setVisible] = useState(true);
  const { peerServer } = useModel('global');
  const resizeVideo = () => {
    console.log('resizeVideo');
    if (!videoRef?.current) return;
    const { width } = videoRef.current!.getBoundingClientRect();
    console.log('x', width);
    videoRef.current.style.flexBasis = computerHeight(width) + 'px';
  };

  const { patient } = useModel('patient');
  const [mixSource, setMixSource] = useState<mixConfig>(null);
  const [muted, setMuted] = useState<boolean>(true);

  const [mixCount, setMixCount] = useState<mixType[]>([]);
  const [recordIndex, setRecordIndex] = useState<number>(-1);
  const [m7sConfig, setM7sConfig] = useState<{
    m7sHost: string;
    m7sType: string;
    m7sStreamPath: string;
  }>({
    m7sHost: '',
    m7sType: '',
    m7sStreamPath: '',
  });
  const { liveControlRecordList, setLiveControlRecordList } =
    useModel('record');

  useEffect(() => {
    const recordIndex = liveControlRecordList!.findIndex(
      (x) => x.id === config?.id,
    );
    console.log('recordIndex', recordIndex);
    setRecordIndex(recordIndex);
  }, [liveControlRecordList]);

  // const setMixSource = outputConfig.outputSource[0]
  useEffect(() => {
    console.log('outputConfig', outputConfig);
    if (!outputConfig) {
      setMixSource({ mixConfig: [], mixType: 0 });
      setMuted(true);
      setMixCount([]);
    } else {
      setMixSource(outputConfig.outputSource[0]);
      const mutedIndex = outputConfig.outputSource[0].mixConfig.findIndex(
        (item) => item.volume > 0,
      );
      setMuted(mutedIndex === -1);
      let mixLength = converMixType(outputConfig.outputSource[0].mixType);
      let deepOut = outputConfig.outputSource[0].mixConfig.slice(0, mixLength);
      setMixCount([...deepOut]);
    }
  }, [outputConfig]);

  //拖拽完成事件
  const updateDropLive = async (index: number, mix: mixType) => {
    outputConfig.outputSource[0].mixConfig.splice(index, 1, mix);
    const mixOutTpe = outputConfig.outputSource[0].mixType;
    outputConfig.outputSource[0].mixConfig.forEach((item, mixIndex) => {
      item.port =
        mixOutTpe === 1 || (mixOutTpe > 900 && mixIndex === 0) ? 5000 : 5001;
    });
    setOutputConfig({ ...outputConfig });
    const result = await updateAppOutPut(config.ip, outputConfig);
    console.log(result);
  };

  //切换分屏类型
  const updateLiveType = async (mixTypes: number) => {
    const mixType = converMixType(mixTypes);
    const length = mixType - outputConfig.outputSource[0].mixConfig.length;
    console.log('mixType', mixType);
    console.log('length', length);
    if (length > 0) {
      outputConfig.outputSource[0].mixConfig.push(
        ...Array(length).fill({
          volume: 0,
          address: '',
          port: 5001,
        }),
      );
    }
    if (length < 0) {
      outputConfig.outputSource[0].mixConfig.splice(mixType);
    }
    if (mixType < 4) {
      outputConfig.outputSource[0].mixConfig.push(
        ...Array(4 - mixType).fill({
          volume: 0,
          address: '',
          port: 5001,
        }),
      );
    }
    outputConfig.outputSource[0].mixConfig.forEach((item, index) => {
      item.port =
        mixTypes === 1 || (mixTypes > 900 && index === 0) ? 5000 : 5001;
    });
    outputConfig.outputSource[0].mixType = mixTypes;
    setOutputConfig({ ...outputConfig });
    console.log('outputConfig', outputConfig);
    const result = await updateAppOutPut(config.ip, outputConfig);
    if (!result.success) {
      message.error('修改失败');
    }
    console.log(result);
  };
  //获取m7s储存参数
  const getM7sConfigInfo = async () => {
    const result = await getM7sConfig(peerServer);
    if (result.status === 200) {
      console.log('setObsServer', result.data);
      setM7sConfig(result.data);
    }
  };
  useEffect(() => {
    const ro = new ResizeObserver(resizeVideo);
    if (videoRef.current) {
      ro.observe(videoRef.current!);
    }
    getM7sConfigInfo();

    // 返回一个清理函数，在组件销毁时调用
    return () => {
      if (videoRef.current) {
        console.log('取消观察');
        ro.disconnect(); // 取消观察
      }
    };
  }, []); // 空数组确保只在组件挂载时运行一次

  const converStream = () => {
    console.log('config.port === 5000', config.port === 5000);
    return `rtmp://${config.ip}/live/${config.port === 5000 ? 'main' : 'sub'}`;
  };
  const startRecord = async () => {
    if (!patient) {
      message.error('请先选择一个患者');
    }
    const fileName = `${dayjs().valueOf()}-${config.id}-${
      config.equipmentName
    }-${mixSource.mixType}`;
    console.log('fileName', fileName);
    let selfGrouthId = 0;
    //推流唯一标识
    const result = await getSelfGrowthId(peerServer);
    if (result.status === 200) {
      console.log('setSelfGrowthId', result.data);
      selfGrouthId = result.data;
      fetch(
        `${
          m7sConfig.m7sHost
        }/rtmp/api/pull?target=${converStream()}&streamPath=${
          m7sConfig.m7sStreamPath
        }-${selfGrouthId}&save=1`,
      )
        .then((data) => {
          console.log('data11111111', data);
          fetch(
            `${m7sConfig.m7sHost}/record/api/start?type=${
              m7sConfig.m7sType
            }&streamPath=${
              m7sConfig.m7sStreamPath
            }-${selfGrouthId}&stream=${converStream()}&fileName=${fileName}&fragment=30s`,
          )
            .then(async (data) => {
              console.log('LiveId', data);
              let recordData: any = {};
              recordData.fileName = fileName;
              recordData.fileUrl = `${m7sConfig.m7sHost}/record/${m7sConfig.m7sType}/${m7sConfig.m7sStreamPath}-${selfGrouthId}/${recordData.fileName}`;
              recordData.uploadType = 1;
              recordData.m7sRecordId = `${m7sConfig.m7sStreamPath}-${selfGrouthId}/${m7sConfig.m7sType}`;
              recordData.recordEquipmentIp = config.ip;
              recordData.patientId = patient.id;
              const addVideoResult = await addVideo(peerServer, recordData);
              if (addVideoResult.status === 200) {
                liveControlRecordList?.push({
                  id: config.id,
                  liveDataId: addVideoResult.data,
                  selfGrouthId: selfGrouthId,
                  m7sRecordId: recordData.m7sRecordId,
                });
                setLiveControlRecordList([...liveControlRecordList]);
                message.success('已开始录制视频');
                await window.tm?.ipcRenderer.invoke('setLiving', true);
              } else {
                console.error('新增录制视频失败：', addVideoResult);
                message.error('新增录制视频失败', addVideoResult);
              }
            })
            .catch((error) => {
              console.error('开始视频录制失败：', error);
              message.error('开始视频录制失败', error);
            });
        })
        .catch((error) => {
          message.error('监听视频流失败');
          console.error('监听视频流失败', error);
        });
    } else {
      message.error('连接服务器失败');
      console.error('连接服务器失败', result);
    }
  };
  const closeRecord = async () => {
    console.log('liveControlRecordList', liveControlRecordList);
    const index = liveControlRecordList?.findIndex((x) => x.id === config.id);
    if (index === -1) {
      message.error('未找到录制开始记录');
      console.error('未找到录制开始记录', liveControlRecordList);
      return;
    }
    const curRecord = liveControlRecordList![index];

    fetch(
      `${m7sConfig.m7sHost}/record/api/stop?id=${m7sConfig.m7sStreamPath}-${curRecord.selfGrouthId}/${m7sConfig.m7sType}`,
    )
      .then(async (data) => {
        console.log('stop to LiveId', data);
        //结束录制后，视频分片处理
        await scanSegmentRecord(
          peerServer,
          liveControlRecordList![index].liveDataId.toString(),
        );
        liveControlRecordList!.splice(index, 1);
        setLiveControlRecordList([...liveControlRecordList]);
        if (liveControlRecordList.length === 0) {
          await window.tm?.ipcRenderer.invoke('setLiving', false);
        }
        message.success('已结束视频录制');
      })
      .catch((error) => {
        console.error('结束视频录制', error);
        message.error('结束视频录制失败');
      });
  };
  const cutImg = async () => {
    if (!patient) {
      message.error('请先选择一个患者');
    }
    const blob = await appPreview(config.ip);
    const formData = new FormData();
    if (blob) {
      formData.append(
        'file',
        blob,
        `${dayjs().valueOf()}-${config.id}-${config.equipmentName}-${
          mixSource.mixType
        }.jpg`,
      );
    }
    console.log('formData', formData);
    const resultUpload = await uploadFormData(peerServer, formData);
    const result = resultUpload.data;
    console.log('result', result);
    if (result && result.status === 200) {
      const data = result.data;
      const fileData = {
        patientId: patient.id,
        fileName: data.fileName,
        fileUrl: data.fileUrl,
        fileTime: 0,
        fileSize: data.fileSize,
        fileType: 1,
        recordTimeNode: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss'),
        recordTime: dayjs(Date.now()).format('YYYY-MM-DD hh:mm:ss'),
        uploadType: 0,
      };
      console.log('fileData', fileData);
      const videoResult = await addVideo(peerServer, fileData);
      console.log('videoResult', videoResult);
      if (videoResult.success) {
        message.success('截图已上传');
      } else {
        message.error('截图失败');
      }
    } else {
      message.error('截图失败');
    }
  };

  const refresh = async () => {
    await reconnectOutPut(config.ip);
  };
  // useUnmount(() => {
  //     setVisible(false)
  // })
  return (
    <>
      {config && (
        <div className={styles.CenterVideoBox}>
          <div className={styles.centerVideo}>
            {
              <div ref={videoRef} className={styles.video}>
                {config.outType === 0 && (
                  <LivePlayer
                    server={config.ip}
                    streamKey={config.port === 5000 ? 'main' : 'sub'}
                    type="Encoder_WebRTC"
                    visible={visible}
                    controls={false}
                    muted={muted}
                  />
                )}
                {
                  //拖拽中并且是分屏状态
                  config.outType === 1 && mixSource && (
                    <div className={styles.container}>
                      {
                        <div
                          className={`${styles[`mix${mixSource.mixType}`]} ${
                            styles.mix
                          }`}
                        >
                          {mixCount.map((mix, index) => {
                            return (
                              <DropContainer
                                key={index}
                                mix={mix}
                                index={index}
                                mixType={mixSource!.mixType}
                                inputDrag={inputDrag}
                                onDrop={async (mix: mixType) => {
                                  console.log('拖动完成' + index);
                                  console.log('mix', mix);
                                  await updateDropLive(index, mix);
                                }}
                              />
                            );
                          })}
                        </div>
                      }
                    </div>
                  )
                }
              </div>
            }
          </div>

          {
            <div className={styles.toolsBox}>
              <div className={styles.first}>
                <Tag
                  color="blue"
                  style={{
                    height: '25px',
                    margin: 'auto 10px',
                  }}
                >
                  {config.port === 5000 ? '主码' : '子码'}
                </Tag>

                {muted && (
                  <NotificationOutlined
                    style={{ fontSize: '30px' }}
                    onClick={async () => {
                      if (config.outType === 1) {
                        outputConfig.outputSource[0].mixConfig.forEach(
                          (item) => {
                            item.volume = 50;
                          },
                        );
                        setOutputConfig({ ...outputConfig });
                        const result = await updateAppOutPut(
                          config.ip,
                          outputConfig,
                        );
                        if (!result.success) {
                          message.error('修改失败');
                        }
                      } else {
                        setMuted(false);
                      }
                    }}
                  />
                )}
                {!muted && (
                  <SoundOutlined
                    style={{ fontSize: '30px' }}
                    onClick={async () => {
                      if (config.outType === 1) {
                        outputConfig.outputSource[0].mixConfig.forEach(
                          (item) => {
                            item.volume = 0;
                          },
                        );
                        setOutputConfig({ ...outputConfig });
                        const result = await updateAppOutPut(
                          config.ip,
                          outputConfig,
                        );
                        if (!result.success) {
                          message.error('修改失败');
                        }
                      } else {
                        setMuted(true);
                      }
                    }}
                  />
                )}

                {config.outType === 0 && (
                  <ScissorOutlined
                    style={{ fontSize: '30px', marginLeft: '20px' }}
                    onClick={async () => await cutImg()}
                  />
                )}

                {config.outType === 0 && (
                  <VideoCameraFilled
                    style={{
                      fontSize: '30px',
                      marginLeft: '20px',
                      color: recordIndex > -1 ? '#fff' : '#5d5d5d',
                    }}
                    onClick={async () => {
                      try {
                        if (recordIndex > -1) {
                          await closeRecord();
                        } else {
                          await startRecord();
                        }
                      } catch (e) {
                        message.error('操作异常');
                        console.error('操作异常', e);
                      }
                    }}
                  />
                )}
              </div>

              <div className={styles.second}>
                {config.outType === 1 && mixSource && (
                  <RectBox
                    mixType={mixSource.mixType}
                    changeRect={async (item) => {
                      console.log(item);

                      await updateLiveType(item);
                    }}
                  />
                )}
              </div>
              <div className={styles.three}>
                {config.outType === 1 && mixSource && (
                  <>
                    <RedoOutlined
                      style={{ fontSize: '30px', marginRight: '20px' }}
                      onClick={async () => {
                        await refresh();
                      }}
                    />

                    <SVG
                      style={{
                        width: '50px',
                        height: '30px',
                        backgroundColor: '#000',
                        fill: '#fff',
                        objectFit: 'fill',
                      }}
                      src="/img/split/清空资源.svg"
                      onClick={async () => {
                        outputConfig.outputSource[0].mixConfig.forEach(
                          (item) => {
                            item.address = '';
                          },
                        );
                        setOutputConfig({ ...outputConfig });
                        const result = await updateAppOutPut(
                          config.ip,
                          outputConfig,
                        );
                        if (!result.success) {
                          message.error('修改失败');
                        }
                      }}
                    />
                  </>
                )}
              </div>
            </div>
          }
        </div>
      )}
      {!config && (
        <div className={styles.CenterVideoBox}>
          <div className={styles.centerVideo}>未选择设备</div>
        </div>
      )}
    </>
  );
};

export default () => {
  const { peerServer } = useModel('global');
  const [inLiveClients, setInLiveClients] = useState<organizationType[]>([]);
  const [outLiveClients, setOutLiveClients] = useState<organizationType[]>([]);
  const [isPlay, setIsPlay] = useState<boolean>(false);
  const [activeLive, setActiveLive] = useState<clientLiveType>(null);
  const [_message, contextHolder] = message.useMessage();
  const [liveFixData, setLiveFixData] = useState<liveFixType>({
    isHover: false,
    startDrag: false,
    config: undefined,
    preview: { x: 0, y: 0 },
  });

  const [inputDrag, setInputDrag] = useState<boolean>(false);
  const [outputConfig, setOutputConfig] = useState<mixOutputSource>(null);

  async function getDeviceList(
    outType: number,
    setList: (client: organizationType[]) => void,
  ) {
    const result: responseType<clientLiveType[]> = await getOutputList(
      peerServer,
      outType,
    ); //0输入 1输出
    console.log('getOutputList', result);
    if (result.success) {
      const deviceList = convertDevice(
        result.data,
        (item, after) => item.organizationId === after.organizationId,
        (after) => {
          return {
            organizationId: after.organizationId,
            organizationName: after.organizationName,
            item: [{ ...after }],
          };
        },
      );
      setList(deviceList);
    } else {
      setList([]);
    }
  }

  useEffect(() => {
    // setLiveClients(dataSource);

    // setActiveLive(dataSource[0])
    // getList()
    getDeviceList(0, setInLiveClients);
    getDeviceList(1, setOutLiveClients);
  }, []);
  useEffect(() => {
    setIsPlay(false);
    setTimeout(() => {
      setIsPlay(true);
    }, 200);
  }, [activeLive]);

  return (
    <div className={styles.liveVideo}>
      {contextHolder}
      {<LiveFix {...liveFixData} />}
      <LeftInput
        liveClients={inLiveClients}
        active={setActiveLive}
        setInputDrag={setInputDrag}
        reloadInList={() => {
          if (activeLive && activeLive.outType === 0) {
            setActiveLive(null);
          }
          getDeviceList(0, setInLiveClients);
        }}
        setLiveFixData={setLiveFixData}
        liveFixData={liveFixData}
      />
      {/*<LivePlayer*/}
      {/*    style={{position:'fix',left:0,top:0}}*/}
      {/*    server={'192.168.0.202'}*/}
      {/*    streamKey={'50001' === '5000' ? 'main' : 'sub'}*/}
      {/*    type="Encoder_WebRTC"*/}
      {/*    visible={true}*/}
      {/*    controls={false}*/}
      {/*    muted={true}*/}
      {/*/>*/}

      <CenterVideo
        config={activeLive}
        inputDrag={inputDrag}
        isPlay={isPlay}
        outputConfig={outputConfig}
        setOutputConfig={setOutputConfig}
      />
      <RightInput
        liveClients={outLiveClients}
        active={setActiveLive}
        setOutputConfig={setOutputConfig}
        reloadOutList={() => {
          if (activeLive && activeLive.outType === 1) {
            setActiveLive(null);
          }
          getDeviceList(1, setOutLiveClients);
        }}
      />
    </div>
  );
};
